package com.dux.shiro1.config;

import com.dux.shiro1.web.error.CodeEnum;
import com.dux.shiro1.web.error.RBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Title: AjaxFilter <br>
 * Description: AjaxFilter <br>
 * Date: 2018年10月22日
 *
 * @author 王东旭
 * @version 1.0.0
 * @since jdk8
 */
public class AjaxFilter extends FormAuthenticationFilter {

    private static final Logger LOG = LoggerFactory.getLogger(AjaxFilter.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Login page view.");
                }
                return true;
            }
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            res.setCharacterEncoding("utf-8");
            res.setContentType("application/json");
            res.setStatus(401);
            try (PrintWriter writer = res.getWriter()){
                String s = objectMapper.writeValueAsString(RBody.error(CodeEnum.UNAUTHORIZED));
                writer.println(s);
            }

            return false;
        }
    }
}
